import{ useEffect, useState } from 'react'
import { NavLink } from 'react-router-dom'
import {
  Card,
  Breadcrumb,
  Button,
  Form,
  Input,
  Space,
  Table,
  Image,
  Switch,
  Pagination,
  Modal,
  Upload,
  message
} from 'antd'
import type { SwiperQuery, Swiper } from '@/types/swiper'
import { getSwiperList, addSwiper, editSwiper, delSwiper } from '@/api/swiper'
import { PlusOutlined } from '@ant-design/icons'
import type {  UploadProps } from 'antd/es/upload'
import type { UploadFile } from 'antd/es/upload/interface'

let bannerid = ''
let fileImg = ''
export default function MySwiper () {
  const items = [
    {
      title: <NavLink to='/'>首页</NavLink>
    },
    {
      title: '轮播图管理'
    },
    {
      title: '轮播图列表'
    }
  ]
  const [form] = Form.useForm()

  const [swiperQuery, setSwiperQuery] = useState({
    page: 1,
    pageSize: 2,
    link: '',
    alt: ''
  } as SwiperQuery)

  const [swiperList, setSwiperList] = useState([] as Swiper[])
  const [total, setTotal] = useState(0)
  const [flag, setFlag] = useState(false)

  // 弹窗是否打开
  const [isModalOpen, setIsModalOpen] = useState(false)
  // 模态值
  const [mode, setMode] = useState('add')
  const [isChecked, setIsChecked] = useState(true)
  const [formModal] = Form.useForm()

  // 获取轮播图列表数据
  const getSwiperListData = async () => {
    const res = await getSwiperList(swiperQuery)

    setSwiperList(res.data.items)
    setTotal(res.data.total)
  }

  useEffect(() => {
    getSwiperListData()
  }, [swiperQuery.page, swiperQuery.pageSize])

  useEffect(() => {
    if (flag) {
      getSwiperListData()
    }
  }, [flag])

  const reset = () => {
    setSwiperQuery({
      ...swiperQuery,
      link: '',
      alt: ''
    })

    form.resetFields()

    setFlag(true)
  }

  const columns = [
    {
      title: '轮播图图片',
      dataIndex: 'img',
      render: (img: string) => {
        return <Image src={img} style={{ width: 90, height: 60 }}></Image>
      }
    },
    {
      title: '跳转地址',
      dataIndex: 'link',
      render: (link: string) => {
        return (
          <a target='__blank' href={link}>
            {link}
          </a>
        )
      }
    },
    {
      title: '轮播图alt',
      dataIndex: 'alt'
    },
    {
      title: '状态',
      dataIndex: 'flag',
      render: (_: any, { flag }: { flag: boolean }) => {
        return <Switch checked={flag} />
      }
    },
    {
      title: 'Action',
      key: 'action',
      render: (_: any, record: any) => (
        <Space size='middle'>
          <Button
            type='primary'
            onClick={() => {
              edit(record)
            }}
          >
            修改
          </Button>
          <Button
            danger
            type='primary'
            onClick={async () => {
              try {
                await modal.confirm({
                  title: '提示',
                  content: '确认退出吗?',
                  onOk: async () => {
                    await delSwiper(record.bannerid)
                    setSwiperQuery({ ...swiperQuery, page: 1 })
                  }
                })
              } catch (error) {}
            }}
          >
            删除
          </Button>
        </Space>
      )
    }
  ]

  // 修改
  const edit = (swiper: Swiper) => {
    bannerid = swiper.bannerid
    setMode('edit')
    formModal.setFieldsValue(swiper)
    setFileList([{ uid: swiper.bannerid, name: swiper.img, url: swiper.img }])
    setIsModalOpen(true)
  }

  // 弹窗确认
  const handleOk = async () => {
    console.log(bannerid)

    try {
      const result = await formModal.validateFields()
      console.log(result)
      result.img = fileImg
      console.log(result)
      if (mode === 'add') {
        await addSwiper(result)
      } else {
        result.bannerid = bannerid
        await editSwiper(result)
      }
      message.success({
        content: mode === 'add' ? '新增轮播图成功' : '修改轮播图成功'
      })

      //完毕后操作
      getSwiperListData()
      setIsModalOpen(false)
      formModal.resetFields()
      setFileList([])
    } catch (error) {
      console.log(error)
    }
  }

  const handleCancel = () => {
    setMode('add')
    setFileList([])
    formModal.resetFields()
    setIsModalOpen(false)
  }

  /**********文件上传+图片预览****************/
  const [fileList, setFileList] = useState<UploadFile[]>([])
  const [previewOpen, setPreviewOpen] = useState(false)
  const [previewImage, setPreviewImage] = useState('')

  // 图片预览
  const handlePreview = (file: UploadFile) => {
    console.log(file)
    setPreviewImage(file.url ?? file.response.fileUrl)
    setPreviewOpen(true)
  }

  const handleChange: UploadProps['onChange'] = ({
    fileList: newFileList,
    file
  }) => {
    // 1、给fileList赋值
    setFileList(newFileList)
    if (file.response) {
      // 2、给表单中的img属性也要赋值，这样校验才能通过
      form.setFieldValue('img', file.response.fileUrl)
      fileImg = file.response.fileUrl
    }

    if (file.status === 'removed') {
      form.setFieldValue('img', '')
      form.validateFields(['img'])
    }
  }

  const [modal, contextHolder] = Modal.useModal()

  return (
    <div>
      <Card>
        <Breadcrumb items={items} />
        <Form
          layout={'inline'}
          form={form}
          style={{ marginTop: 20 }}
          size='large'
        >
          <Form.Item label='跳转链接' name='link'>
            <Input
              placeholder='请输入跳转链接'
              value={swiperQuery.link}
              onChange={e => {
                setSwiperQuery({ ...swiperQuery, link: e.target.value })
              }}
            />
          </Form.Item>
          <Form.Item label='图片alt' name='alt'>
            <Input
              placeholder='请输入图片alt'
              value={swiperQuery.alt}
              onChange={e => {
                setSwiperQuery({ ...swiperQuery, alt: e.target.value })
              }}
            />
          </Form.Item>
          <Form.Item>
            <Space />
            <Button type='default' style={{ marginRight: 20 }} onClick={reset}>
              清空
            </Button>
            <Button
              type='primary'
              style={{ marginRight: 20 }}
              onClick={getSwiperListData}
            >
              搜索
            </Button>
            <Button type='default' onClick={() => setIsModalOpen(true)}>
              +新增轮播图
            </Button>
          </Form.Item>
        </Form>
      </Card>
      <Card style={{ marginTop: 10 }}>
        <Table
          columns={columns}
          dataSource={swiperList}
          rowKey='bannerid'
          pagination={false}
        />
        <Pagination
          style={{ marginTop: 20, textAlign: 'center' }}
          current={swiperQuery.page}
          pageSize={swiperQuery.pageSize}
          total={total}
          pageSizeOptions={[2, 4, 6]}
          showSizeChanger
          showQuickJumper
          showTotal={total => `共 ${total} 页`}
          onChange={(page, pageSize) => {
            setSwiperQuery({ ...swiperQuery, page, pageSize })
          }}
        />
      </Card>

      <Modal
        title={mode === 'add' ? '新增轮播图' : '修改轮播图'}
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form
          form={formModal}
          size='large'
          labelCol={{ span: 5 }}
          wrapperCol={{ span: 19 }}
          initialValues={{ flag: true }}
        >
          <Form.Item
            label='轮播图图片'
            name='img'
            rules={[{ required: true, message: '请上传图片!' }]}
          >
            <div>
              <Upload
                action={`${import.meta.env.VITE_BASEURL}file/upload`}
                listType='picture-card'
                fileList={fileList}
                onPreview={handlePreview}
                onChange={handleChange}
              >
                {fileList.length >= 1 ? null : <PlusOutlined />}
              </Upload>
              <Modal
                open={previewOpen}
                title='图片预览'
                footer={null}
                onCancel={() => setPreviewOpen(false)}
              >
                <img
                  alt='example'
                  style={{ width: '100%' }}
                  src={previewImage}
                />
              </Modal>
            </div>
          </Form.Item>
          <Form.Item
            label='跳转链接'
            name='link'
            rules={[{ required: true, message: '请输入轮播图链接!' }]}
          >
            <Input placeholder='请输入跳转链接' />
          </Form.Item>
          <Form.Item label='alt说明' name='alt'>
            <Input placeholder='请输入alt说明' />
          </Form.Item>
          <Form.Item label='状态' name='flag'>
            <Switch
              checked={isChecked}
              onChange={isChecked => setIsChecked(isChecked)}
            />
          </Form.Item>
        </Form>
      </Modal>

      {contextHolder}
    </div>
  )
}
